<template>
  <vab-card
    shadow="always"
    v-loading="loading"
    element-loading-background="rgba(122, 122, 122, 0.6)"
  >
    <template #header>
      <div class="flex leve2_title">
        产品价格明细
        <span class="pour_text flex">注： <sapn class="required_text">*</sapn> 为必填项</span>
      </div>
    </template>
    <div :class="{ 'warn': isWarn }">
      <el-form
        :ref="(el) => productFormRef = el"
        :model="productList"
        class="formData"
      >
        <el-table
          border
          height="300px"
          :data="productList"
          v-loading="tableLoading"
        >
          <el-table-column align="center" width="40" fixed="left">
            <template #default="scope">
              <label
                class="el-checkbox"
                :class="{ 'is-checked': radioKey == scope.id }"
                @click="handleCurrentChange(scope.row)"
              >
                <span
                  class="el-checkbox__input"
                  :class="{ 'is-checked': radioKey == scope.id }"
                >
                  <span class="el-checkbox__inner"></span>
                </span>
              </label>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" width="60">
            <template #default="props">
              {{ props.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="goods_no" align="center" min-width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>产品编码</span>
              <vab-icon icon="search-line" style="color: #0967f4; margin-left: 12px;" @click="handleLookAll"/>
            </template>
            <template #default="props">
              <el-form-item prop="number" >
                <LazySelect v-model:value="props.row.number" :clearable="false" :userOrgId="userOrgId" type="number" @LazyChange="(value) => {
                  productQuerySearch(value, 'number', props.$index, 'number')
                }"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goods_name" align="center" min-width="300">
            <template #header>
              <span class="required_text">*</span>
              <span>产品名称</span>
              <vab-icon icon="search-line" style="color: #0967f4; margin-left: 12px;" @click="handleLookAll"/>
            </template>
            <template #default="props">
              <el-form-item prop="name">
                <LazySelect v-model="props.row.name" :clearable="false" :userOrgId="userOrgId" type="" @LazyChange="(value) => {
                  productQuerySearch(props.row.name, 'number', props.$index, 'name')
                }"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="specification" align="center" width="140">
            <template #header>
              <span>规格型号</span>
            </template>
            <template #default="props">
              <span
                class="ellipsis"
                v-text="_FieldFormat(props.row.specification)"
              ></span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="batch_no"
            label="批次号"
            align="center"
            width="150"
          >
            <template #default="props">
              <el-form-item prop="batch_no">
                <el-select
                  v-model="props.row.batch_no"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in props.row.stock_batch"
                    :key="item.batch_no"
                    :label="item.batch_no"
                    :value="item.batch_no"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="price" align="center" width="170">
            <template #header>
              <span class="required_text">*</span>
              <span>价格</span>
            </template>
            <template #default="props">
              <el-form-item prop="price">
                <el-input-number
                  :min="0"
                  :precision="2"
                  :controls="false"
                  class="width_100"
                  placeholder="价格不可低于底价"
                  v-model.trim="props.row.price"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="unit_name" align="center" width="150">
            <template #header>
              <span class="required_text">*</span>
              <span>计价单位</span>
            </template>
            <template #default="props">
              <span class="ellipsis">
                {{ props.row.unit_name || '--' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="base_price" align="center" width="140">
            <template #header>
              <span class="required_text">*</span>
              <span>底价</span>
            </template>
            <template #default="props">
              {{ _FieldFormat(props.row.base_price, 'money', 2) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="70">
            <template #default="props">
              <vab-icon
                icon="add-circle-line"
                class="icon_color"
                @click="handleAdd(props.row)"
              />
              <vab-icon
                icon="delete-bin-5-line"
                @click="handleRemove(props.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <ProductsAll ref="productsAllRef" :userOrgId="userOrgId" @handleShareSave="handleShareSave"/>
  </vab-card>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ProductsInformation',
})
/**
 * @props
 */
defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  isWarn: {
    type: Boolean,
    default: false,
  }
})
/**
 * @import
 */
import { ref } from 'vue'
import ProductsAll from './ProductsAll.vue'
import { FieldFormat, FilterRepeat, StrSplit } from '/@/utils/utils'
import {
  getProductList,
} from '/@/api/dms/product'
import { ElMessage, FormRules } from 'element-plus';
import LazySelect from '/@/components/lazySelect/index.vue'
import { _Message } from '~/src/utils/message'
/**
 * @var
 */
const tableLoading = ref(false)
const proxy: any = getCurrentInstance()?.proxy

const productFormRef = ref()
const name = ref<any>([])

const productsAllRef = ref<any>(null)
const userOrgId = ref('') //使用组织id
// 基础五个数据
const productList = ref<any>([])
for (let index = 0; index < 5; index++) {
  productList.value.push({
    down_price: 0,
    base_price: 0
  })
}

const oldProductList = ref<any>(productList)

const currentRow = ref<any>() //选中块
const radioKey = ref<any>(-1) //唯一值
const copyData = ref<any>([]) //拿到的复制数据

interface RuleForm {
  name: string,
  number: string,
  price: string | number
}

const rules = reactive<FormRules<RuleForm>>({
  price: [
    { required: true, message: '价格不能为空', trigger: 'blur' },
  ]
})
/**
 * @method
 */

const emit = defineEmits(['checkUseOrg'])

// 添加
const handleAdd = (row: any) => {
  productList.value.push({
    down_price: 0,
    base_price: 0,
    forbid_status: 0,
  })
}
// 删除
const handleRemove = (index: number) => {
  productList.value.splice(index, 1)
}

// 单选
const handleCurrentChange = (row: any) => {
  radioKey.value = row.id
  currentRow.value = row
}
const _FieldFormat = (value: string, type = '', radio = 2) => {
  return FieldFormat(value, type, radio)
}

// 查看全部产品
const handleLookAll = () => {
  if (!userOrgId.value) {
    _Message('请选择使用组织后再进行操作', 'warning')
    return
  }
  productsAllRef.value._GetProductList()
}

// 校验使用组织是否选择
const LazyFocus = () => {
  emit('checkUseOrg')
}

// 查询
const querySearch = async () => {
  if (JSON.stringify(name.value) == '[]') {
    productList.value = []
    return
  }

  tableLoading.value = true
  await _getProductList()
  ElMessage.success('查询成功')
  tableLoading.value = false

}
// 重置数据
const resetData = (value: any) => {
  // // 使用组织清空操作
  // if (userOrgId.value && userOrgId.value != value) productList.value = [{}]

  userOrgId.value = value
  // 重置查看全部筛选项
  productsAllRef.value.handleReset()

}

// 产品价格带出基本信息
const productQuerySearch = async (value: string | number, type = '', index = 0, lay = 'number') => {

  const res = await getProductList({
    page: 1,
    limit: 2000,
    type: 1,
    filter: { number: type == 'number' ? value : '', name: type == 'name' ? value : '' },
  })


  let row = res.data.list[0]

  // 判断产品名称不能选中，来回切换报警
  if (lay == 'name') {
    if (productList.value[index].number == value) {
      productList.value[index].name = row.name
      return
    }
  }

  if (productList.value.length > 1) {

    let voidNumber = false
    voidNumber = productList.value.some((item: any) => item.number == row.number)

    if (voidNumber) {
      proxy.$Message('编码重复,请重新选择！', 'warning')
      productList.value[index] = {
        down_price: 0,
        base_price: 0,
      }
      return
    }
  }

  productList.value[index] = {
    ...row,
    price: '',
    down_price: row.base_price,
    forbid_status: 0,
    product_id: row.id,
    product_name: row.name,
    product_number: row.number,
    stock_batch: row.stock_batch,
    batch_no: '',
    id: 0,
  }
}

const _getProductList = async () => {

  if (JSON.stringify(name.value) == '[]') return

  let res = await getProductList({
    page: 1,
    limit: 2000,
    type: 1,
    filter: { number: [], name: name.value || [], use_org_id: userOrgId.value },
  })

  if (!res.data.list.length) {
    name.value = []
    return
  }

  const list = await res.data.list.map((item: any) => {
    return {
      ...item,
      price: 0,
      product_id: item.id,
      product_name: item.name,
      product_number: item.number,
      id: 0,
    }
  })

  productList.value = [...list, ...copyData.value]
}


const getScreen = async () => {
}

// 查看全部 返回数据
const handleShareSave = (list: any) => {
  if (!list.length) return
  tableLoading.value = true
  // 筛选合适的
  const _productList = productList.value.filter((item: any) => { return item.number })
  // 合并
  const Array = list.concat(_productList)
  // 去重
  productList.value = FilterRepeat(Array, 'number')
  tableLoading.value = false
}

// 获取复制数据
const getUpdateData = async (res: any) => {
  let array: any[] = []

  const list = res.product.filter((item: any) => item.row_audit_status != 8)

  tableLoading.value = true
  copyData.value = []
  copyData.value = await list.map((item: any) => {
    array.push(item.number)
    return {
      ...item,
      row_audit_status: 0,
      priceDisabled: true,
      productDisabled: true,
      base_price: item.down_price || 0, //底价
      forbid_status: item.forbid_status || 1, //是否失效
    }
  })

  productList.value = copyData.value
  tableLoading.value = false
  name.value = array
}

/**
 * @实例
 */

//抛出数据
defineExpose({
  productFormRef,
  productList,
  getScreen,
  resetData,
  getUpdateData,
  _getProductList
})
onMounted(() => {
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-loading-spinner {
    display: none;
  }
}

.products_font1 {
  font-size: 16px;
  margin-bottom: 15px;
}

.products_div {
  width: 300px;
}

.products_div1 {
  margin-right: 20px;
  margin-left: 10px;
  display: inline-block;

  :deep() {
    .el-input__wrapper {
      border-bottom-right-radius: 0px !important;
      border-top-right-radius: 0px !important;
      border-right: 0px solid !important;
    }

    .el-button {
      border-bottom-left-radius: 0px !important;
      border-top-left-radius: 0px !important;
      border-left: 0px solid !important;
    }
  }
}

.products_font2 {
  color: rgb(245, 154, 35);
  margin-left: 20px;
}

.products_div2 {
  margin-right: 20px;
}

.products_div3 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  margin-top: 25px;
}

.formData {
  :deep() {
    .el-form-item {
      margin-bottom: 0px;
    }
  }

  .icon_color {
    color: #0967f4;
    margin-right: 4px;
  }
}

.warn {
  border: 2px dashed red;
}
</style>
